package DMSXL._2024.BinaryTrees;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class maxPathSum {
    public static void main(String[] args) {

    }
    int maxSum = Integer.MIN_VALUE;
    public int maxPathSum(TreeNode root) {
        maxGain(root);
        return maxSum;
    }

    public int maxGain(TreeNode node) {
        if (node == null) {
            return 0;
        }

        // 递归计算左右子节点的最大贡献值
        // 只有在最大贡献值大于 0 时，才会选取对应子节点
        int left = Math.max(maxGain(node.left),0);
        int right = Math.max(maxGain(node.right),0);

        maxSum = Math.max(maxSum,node.val + left + right);

        return node.val + Math.max(left,right);
    }

}
